/*
 * @Autor: Ruohong Yu
 * @Date: 2023-02-21 19:23:04
 * @Description: file content
 * @FilePath: \ebookd:\program\vsc\ebook\node-ebook\app.js
 */
const express = require('express')
const cors = require('cors')
const config = require('./bin/const')
const app = express()
const expressJWT = require('express-jwt')
const joi = require('joi')
const bodyParser = require('body-parser')
const userRouter = require('./routes/user')
const bookRouter= require('./routes/book')
const shelfRouter=require('./routes/shelf')
const userinfoRouter=require('./routes/userinfo')

app.use(cors())
app.use('/public/', express.static('./public/'))
app.use('/my',expressJWT({ secret: config.myjwtkey.jwtSecretKey }))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(userRouter)
app.use(bookRouter)
app.use(shelfRouter)
app.use(userinfoRouter)

// 错误中间件
app.use(function (err, req, res, next) {
  // 数据验证失败
  if (err instanceof joi.ValidationError) return res.send({ status: 1, message: err.message })
  //token验证失败
  if (err.name === 'UnauthorizedError') return res.send({ status: 1, message: err.message, code:10 })
  res.send({ status: 1, message: err.message })
})

app.get('/',(req,res)=>{
  res.send('aa')
})

const server = app.listen(3000, ()=>{
  const host = server.address().address
  const port = server.address().port
  console.log('server is listening at http://%s:%s',host,port)
})
